package com.zh.system.monitor;

import com.alibaba.fastjson.JSON;
import com.zh.system.config.WebSocketConfig;
import com.zh.web.domain.system.dto.MessageDto;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * websocket 服务端点。注意：websocket对象是多例的
 */
@EqualsAndHashCode(callSuper = true)
@Slf4j
@Service
@ServerEndpoint(value = "/ws/monitor/{userId}", configurator = WebSocketConfig.class)
@Data
@ToString(callSuper = true)
public class SystemMonitor extends TextWebSocketHandler {
    // 用于存储每个用户客户端对象 userId-websocketServer
    public static Map<Long, SystemMonitor> onlineUserMap = new ConcurrentHashMap<>();
    // 用户id
    private Long userId;
    // 会话
    private Session session;
//    private RoleClient roleClient = SpringUtils.getBean(RoleClient.class);

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId, EndpointConfig config) {
        //1.键为用户id
        this.session = session;
        //暂时不写身份校验 登录页面已校验管理员,如果需要后面再加
//        List<RoleVo> roleVoList = roleClient.getRoleByUserId(userId).getData();
//        boolean isAdmin = roleVoList.stream().anyMatch(roleVo -> ProtectedRole.ADMIN.getRoleCode().equals(roleVo.getRoleCode()));
        if (true) {
            this.userId = userId;
            session.getUserProperties().put("userId", userId);
            if (onlineUserMap.get(userId) == null) {
                onlineUserMap.put(userId, this);
                log.info("收到来自窗口的连接，id={},session={}", userId, this.session);
                MessageDto messageDto = MessageDto.builder()
                        .content("连接成功\n")
                        .type("info")
                        .sendTime(LocalDateTime.now())
                        .build();
                sendMessage(messageDto, this.session);
            } else {
                log.warn("用户id已存在，id={}", userId);
                MessageDto messageDto = MessageDto
                        .builder()
                        .type("info")
                        .sendTime(LocalDateTime.now())
                        .content("请勿重复连接\n")
                        .build();
                sendMessage(messageDto, this.session);
            }
        } else {
            try {
                session.close();
            } catch (IOException e) {
                log.error("关闭会话连接时失败", e);
                throw new RuntimeException(e);
            }
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到来自窗口[{}]的的信息: {}", this.session, message);
        String returnMessage = "返回消息\n";
        MessageDto messageDto = MessageDto
                .builder()
                .sendTime(LocalDateTime.now())
                .type("info")
                .content(returnMessage).build();
        sendMessage(messageDto, this.session);
    }

    @OnClose
    public void onClose(Session session) {
        MessageDto messageDto = MessageDto
                .builder()
                .sendTime(LocalDateTime.now())
                .type("info")
                .content("已断开连接").build();
        sendMessage(messageDto, this.session);
        onlineUserMap.values().removeIf(websocketServer -> websocketServer.session.equals(session));
        log.info("有一连接[{}-{}]关闭！当前连接数为 {}", this.userId, this.session, onlineUserMap.size());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("{} 连接发生错误", this.userId, throwable);
        onlineUserMap.values().removeIf(websocketServer -> websocketServer.session.equals(session));
    }

    /**
     * 給session连接推送消息
     */
    public void sendMessage(MessageDto message, Session session) {
        try {
            session.getAsyncRemote().sendText(JSON.toJSONString(message));
            log.info("发送给某用户 success");
        } catch (Exception e) {
            log.error("发送给某用户发生错误", e);
        }
    }

    /**
     * 給session连接推送消息
     */
    public String sendMessage(String message, Session session) {
        try {
            session.getAsyncRemote().sendText(message);
            return "发送给某用户 success";
        } catch (Exception e) {
            log.error("发送给某用户发生错误", e);
            return "发送给某用户 error";
        }
    }

    //todo
    public void sendMessageToGroup(String message, Long groupId) {
        return;
    }

    /**
     * 向所有连接群发消息
     */
    public static void sendMessageToAll(MessageDto message) {
        for (SystemMonitor item : onlineUserMap.values()) {
            try {
                item.sendMessage(message, item.getSession());
            } catch (Exception e) {
                log.error("向客户端推送数据发生错误", e);
            }
        }
    }

    /**
     * 向所有连接群发消息
     */
    public static void sendMessageToAll(String message) {
        for (SystemMonitor item : onlineUserMap.values()) {
            try {
                item.sendMessage(message, item.getSession());
            } catch (Exception e) {
                log.error("向客户端推送数据发生错误", e);
            }
        }
    }
}
